/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Windows.Input;
using System.Collections.Generic;

#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for MessageBox.xaml
    /// </summary>
    public partial class DateTimePicker : ModalWindow
    {
        private bool isFirstEntry = true;
        private bool shouldAskForEndDate = false;
        private string customMessage = null;

        public DateTimePicker(bool showUserButton,
            bool showGroupButton,
            bool showTransactionTypesButton,
            bool askForEndDate,
            bool showTimePanel,
            string message = null,
            DateTime? selectedDateTime = null)
            : base()
        {
            if (PosWindow.MainPosWindow != null)
            {
                PosWindow.MainPosWindow.Topmost = false;
            }
            this.InitializeComponent();
            shouldAskForEndDate = askForEndDate;
            if (!showTimePanel)
            {
                canvasTimePanel.Visibility = System.Windows.Visibility.Hidden;
            }
            if (!showGroupButton)
            {
                stackPanelButtons.Children.Remove(buttonByGroup);
            }
            if (!showUserButton)
            {
                stackPanelButtons.Children.Remove(buttonByUser);
            }
            if (!showTransactionTypesButton)
            {
                stackPanelButtons.Children.Remove(buttonByPayType);
            }

            customMessage = message;
            Reset(customMessage);

            buttonNo.MouseDown += new MouseButtonEventHandler(buttonNo_MouseDown_NOTHROW);
            buttonYes.MouseDown += new MouseButtonEventHandler(buttonYes_MouseDown_NOTHROW);
            this.Closing += new System.ComponentModel.CancelEventHandler(MessageBox_Closing_NOTHROW);

            _hoursOfDayIdx = 0;
            _minutesOfDayIdx = 0;
            _ampmOfDayIdx = 0;

            LastSelectedUser = null;
            lastChosenDbUserId = DominicaEntities.CONST_ALL_DB_OBJECTS_WILDCARD;
            LastChosenDbProductGroupId = DominicaEntities.CONST_ALL_DB_OBJECTS_WILDCARD;
            LastSelectedProductGroup = null;

            if (selectedDateTime != null)
            {
                calendar.SelectedDate = selectedDateTime;
                LastStartSelectedDateTime = (DateTime)selectedDateTime;

                if (LastStartSelectedDateTime.Hour >= 13)
                {
                    _ampmOfDayIdx = 1; ///Make PM
                    _hoursOfDayIdx = lastSelectedStartDateTime.Hour - 13;
                }
                else
                {
                    _ampmOfDayIdx = 0; ///Make AM
                    _hoursOfDayIdx = lastSelectedStartDateTime.Hour - 1;
                }

                _minutesOfDayIdx = selectedDateTime.Value.Minute;

            }
            else
            {
                LastStartSelectedDateTime = DateTime.Now;
            }

            textBlockHour.Text = _hoursOfDay[_hoursOfDayIdx];
            textBlockMinute.Text = _minutesOfDay[_minutesOfDayIdx];
            textBlockAMPM.Text = _ampmOfDay[_ampmOfDayIdx];
        }


        protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseUp(e);
            if (Mouse.Captured is System.Windows.Controls.Primitives.CalendarItem)
            {
                Mouse.Capture(null);
            }
        } 


        private void Reset(string message)
        {
            isFirstEntry = true;
            if (message == null)
            {
                textBlockMessage.Text = "Please Select a Report Start Date";
            }
            else
            {
                textBlockMessage.Text = message;
            }
        }

        static DateTimePicker()
        {
            for (int i = 1; i <= 12; i++)
            {
                _hoursOfDay.Add(i.ToString());
            }

            for (int i = 0; i <= 59; i += 1)
            {
                if (i < 10)
                {
                    _minutesOfDay.Add("0" + i.ToString());
                }
                else
                {
                    _minutesOfDay.Add(i.ToString());
                }
            }

            _ampmOfDay.Add("AM");
            _ampmOfDay.Add("PM");
        }

        public static UserResponse LastResponse
        {
            get;
            set;
        }

        private static List<string> _hoursOfDay = new List<string>(12);
        private static int _hoursOfDayIdx = 0;

        private static List<string> _minutesOfDay = new List<string>(60);
        private static int _minutesOfDayIdx = 0;

        private static List<string> _ampmOfDay = new List<string>(2);
        private static int _ampmOfDayIdx = 0;

        private static DateTime lastSelectedStartDateTime;
        public static DateTime LastStartSelectedDateTime
        {
            get { return DateTimePicker.lastSelectedStartDateTime; }
            set { DateTimePicker.lastSelectedStartDateTime = value; }
        }

        private static DateTime lastSelectedEndDateTime;
        public static DateTime LastEndSelectedDateTime
        {
            get { return DateTimePicker.lastSelectedEndDateTime; }
            set { DateTimePicker.lastSelectedEndDateTime = value; }
        }

        private static string lastSelectedUser;
        public static string LastSelectedUser
        {
            get { return DateTimePicker.lastSelectedUser; }
            set { DateTimePicker.lastSelectedUser = value; }
        }

        private static Int64 lastChosenDbUserId;
        public static Int64 LastChosenDbUserId
        {
            get { return DateTimePicker.lastChosenDbUserId; }
            set { DateTimePicker.lastChosenDbUserId = value; }
        }

        private static string lastSelectedProductGroup;
        public static string LastSelectedProductGroup
        {
            get { return DateTimePicker.lastSelectedProductGroup; }
            set { DateTimePicker.lastSelectedProductGroup = value; }
        }

        private static Int64 lastChosenDbProductGroupId;
        public static Int64 LastChosenDbProductGroupId
        {
            get { return DateTimePicker.lastChosenDbProductGroupId; }
            set { DateTimePicker.lastChosenDbProductGroupId = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MessageBox_Closing_NOTHROW(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                ModalDialogIsOpen = false;
                CurrentlyOpenInstance = null;

#if !_DEBUG
                if (PosWindow.MainPosWindow != null)
                {
                    PosWindow.MainPosWindow.Topmost = true;
                }
#endif
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_YESNO_CLOSING, exc);
            }
        }
        void buttonYes_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                LastResponse = UserResponse.YES;
                if (shouldAskForEndDate)
                {
                    if (isFirstEntry)
                    {
                        buttonByGroup.Visibility = System.Windows.Visibility.Hidden;
                        buttonByUser.Visibility = System.Windows.Visibility.Hidden;
                        buttonByPayType.Visibility = System.Windows.Visibility.Hidden;

                        if (calendar.SelectedDate != null)
                        {
                            DateTime dt = (DateTime)calendar.SelectedDate;
                            int militaryHour = 0;
                            int minutesOfDay = 0;

                            Int32.TryParse(_hoursOfDay[_hoursOfDayIdx], out militaryHour);
                            Int32.TryParse(_minutesOfDay[_minutesOfDayIdx], out minutesOfDay);

                            if (_ampmOfDayIdx == 1)
                            {
                                if (militaryHour != 12)
                                {
                                    militaryHour += 12;
                                }
                            }
                            LastStartSelectedDateTime = new DateTime(dt.Year, dt.Month, dt.Day, militaryHour, minutesOfDay, 0);
                        }
                        else
                        {
                            LastStartSelectedDateTime = DateTime.Now;
                        }

                        isFirstEntry = false;
                        textBlockMessage.Text = "Please Select a Report End Date";
                    }
                    else
                    {
                        if (calendar.SelectedDate != null)
                        {
                            DateTime dt = (DateTime)calendar.SelectedDate;
                            int militaryHour = 0;
                            int minutesOfDay = 0;

                            Int32.TryParse(_hoursOfDay[_hoursOfDayIdx], out militaryHour);
                            Int32.TryParse(_minutesOfDay[_minutesOfDayIdx], out minutesOfDay);

                            if (_ampmOfDayIdx == 1)
                            {
                                if (militaryHour != 12)
                                {
                                    militaryHour += 12;
                                }
                            }
                            LastEndSelectedDateTime = new DateTime(dt.Year, dt.Month, dt.Day, militaryHour, minutesOfDay, 0);
                        }
                        else
                        {
                            LastEndSelectedDateTime = DateTime.Now;
                        }

                        this.Close();
                    }
                }
                else
                {
                    if (calendar.SelectedDate != null)
                    {
                        DateTime dt = (DateTime)calendar.SelectedDate;
                        int militaryHour = 0;
                        int minutesOfDay = 0;

                        Int32.TryParse(_hoursOfDay[_hoursOfDayIdx], out militaryHour);
                        Int32.TryParse(_minutesOfDay[_minutesOfDayIdx], out minutesOfDay);

                        if (_ampmOfDayIdx == 1)
                        {
                            if (militaryHour != 12)
                            {
                                militaryHour += 12;
                            }
                        }
                        LastStartSelectedDateTime = new DateTime(dt.Year, dt.Month, dt.Day, militaryHour, minutesOfDay, 0);
                    }
                    else
                    {
                        LastStartSelectedDateTime = DateTime.Now;
                    }
                    this.Close();
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_YESNO_YES_MOUSE_DOWN, exc);
            }
        }

        void buttonNo_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                LastResponse = UserResponse.NO;
                this.Close();
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_YESNO_NO_MOUSE_DOWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="msg"></param>
        public void SetMessage(String msg)
        {
            textBlockMessage.Text = msg;
        }

        private void buttonHourLeft_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _hoursOfDayIdx -= 1;
            if (_hoursOfDayIdx < 0)
            {
                _hoursOfDayIdx = _hoursOfDay.Count - 1;
            }
            textBlockHour.Text = _hoursOfDay[_hoursOfDayIdx];
        }

        private void buttonHourRight_MouseDown(object sender, MouseButtonEventArgs e)
        {

            _hoursOfDayIdx += 1;
            if (_hoursOfDayIdx > _hoursOfDay.Count - 1)
            {
                _hoursOfDayIdx = 0;
            }
            textBlockHour.Text = _hoursOfDay[_hoursOfDayIdx];

        }

        private void buttonMinuteLeft_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _minutesOfDayIdx -= 1;
            if (_minutesOfDayIdx < 0)
            {
                _minutesOfDayIdx = _minutesOfDay.Count - 1;
            }
            textBlockMinute.Text = _minutesOfDay[_minutesOfDayIdx];
        }

        private void buttonMinuteRight_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _minutesOfDayIdx += 1;
            if (_minutesOfDayIdx > _minutesOfDay.Count - 1)
            {
                _minutesOfDayIdx = 0;
            }
            textBlockMinute.Text = _minutesOfDay[_minutesOfDayIdx];
        }

        private void buttonAMPMLeft_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _ampmOfDayIdx -= 1;
            if (_ampmOfDayIdx < 0)
            {
                _ampmOfDayIdx = _ampmOfDay.Count - 1;
            }
            textBlockAMPM.Text = _ampmOfDay[_ampmOfDayIdx];
        }

        private void buttonAMPMRight_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _ampmOfDayIdx += 1;
            if (_ampmOfDayIdx > _ampmOfDay.Count - 1)
            {
                _ampmOfDayIdx = 0;
            }
            textBlockAMPM.Text = _ampmOfDay[_ampmOfDayIdx];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonByUser_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                LastSelectedUser = USER.PopupSelectUser(out lastChosenDbUserId);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonByGroup_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                LastSelectedProductGroup = PRODUCT_GROUP.PopupSelectProductGroup(out lastChosenDbProductGroupId);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        private void buttonByPayType_MouseDown(object sender, MouseButtonEventArgs e)
        {

        }
    }
}
